using System.Collections;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine;

public class UpgradeRewindTime:Upgrade {

	const int queueSize = 30;

	Vector2[] positionQueue = new Vector2[queueSize];
	float[] hpQueue = new float[queueSize];
	int endIndex;
	float timeAfterRecord;

	public override void OnEquip() {
		base.OnEquip();
		for(int i = 0;i<queueSize;i++) {
			positionQueue[i]=weapon.owner.position;
			hpQueue[i]=weapon.owner.HP;
		}
		endIndex=queueSize-1;
	}

	public override void Update(object sender,WeaponEventArgs e) {
		base.Update(sender,e);
		timeAfterRecord+=deltaTime;
		if(timeAfterRecord>0.1f) {
			timeAfterRecord-=0.1f;
			endIndex=(endIndex+1)%queueSize;
			positionQueue[endIndex]=weapon.owner.position;
			hpQueue[endIndex]=weapon.owner.HP;
		}

		if(shieldAdded>0) {
			float currentShield = weapon.owner.buffs[typeof(BuffDamageShield)].stacks;
			if(currentShield<=shieldMin) {
				shieldAdded=0;
			} else {
				float decrease = deltaTime*0.5f;
				if(decrease>shieldAdded) decrease=shieldAdded;
				if(decrease>currentShield-shieldMin) decrease=currentShield-shieldMin;
				shieldAdded-=decrease;
				weapon.owner.buffs[typeof(BuffDamageShield)].stacks-=decrease;
			}
		}
	}

	float shieldAdded;
	float shieldMin;

	protected override void ReloadingEventHandler(object _sender,ReloadEventArgs e) {
		base.ReloadingEventHandler(_sender,e);
		int sourceIndex = endIndex-Mathf.RoundToInt((e.ammoAdded/(float)e.stat.clipSize)*20);
		if(sourceIndex<0) sourceIndex+=queueSize;
		weapon.owner.transform.position=positionQueue[sourceIndex];
		float damageTaken = hpQueue[sourceIndex]-weapon.owner.HP;
		if(damageTaken>0) {
			weapon.owner.buffs[typeof(BuffDamageShield)].stacks+=damageTaken*0.1f;
			shieldAdded+=damageTaken*0.1f;
			shieldMin=weapon.owner.buffs[typeof(BuffDamageShield)].stacks-shieldAdded;
		}
	}

}
